import { Table, Tag, Radio, Button, Form, Input, Select, Drawer } from 'antd';
import { EyeTwoTone, SettingOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import {
  userAllApi,
  roleAllApi,
  deptAllApi,
  addUserApi,
  deleteUserApi,
} from '../../apis/menuApi';
import { DataType, IAddUser } from '../../types/user';
import { message } from 'antd';
import FormData from '../../utils/FormData';
import SearchUse from './user/searchUse';

const { Option } = Select;

export default function user() {
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(Number);
  const [roleList, setRoleList] = useState([]);
  const [deptList, setDeptList] = useState([]);
  const [rowId, setRowId] = useState({});
  const [visible, setVisible] = useState(false);
  const [updateVisible, setUpdateVisible] = useState(false);
  // const [revise, setRevise] = useState(false)
  const [reviseList, setReviseList] = useState({});
  const [value, setValue] = useState(1);
  const [updateForm] = Form.useForm();
  const [form] = Form.useForm();
  const [, forceUpdate] = useState({});

  //调用生命周期
  useEffect(() => {
    userData(1, 10);
  }, []);
  useEffect(() => {
    // console.log(reviseList);
  }, [reviseList]);

  useEffect(() => {
    forceUpdate({});
  }, []);

  const onFinish = (values: any) => {
    console.log('Finish:', values);
  };

  //发送请求获取菜单数据
  const userData = async (page: number, pageSize: number) => {
    const data = {
      pageSize: pageSize,
      pageNum: page,
    };
    const res = await userAllApi(FormData(data));
    res.rows.map((item: any, index: number) => {
      return (item.key = item.userId);
    });
    setTotal(res.total);
    setData(res.rows);
  };

  // 表格单选框
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
      setRowId(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.username === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  //新增相关
  //点击出现侧边栏
  const showDrawer = () => {
    setVisible(true);
    roleData();
    deptData();
  };
  //点击退出侧边栏
  const onClose = () => {
    setVisible(false);
    setUpdateVisible(false);
  };

  //获取角色信息
  const roleData = async () => {
    const res = await roleAllApi();
    console.log(res);
    setRoleList(res.rows);
  };
  //获取部门信息
  const deptData = async () => {
    const res = await deptAllApi();
    setDeptList(res.rows.children);
  };

  //提交新增
  const addUser = async (values: IAddUser) => {
    console.log(values);

    if (values.roleId) {
      values.roleId = values.roleId.toString();
    }
    const rep = await addUserApi(values);
    if (rep) {
      message.success('新增成功！');
      setVisible(false);
      userData(1, 10);
    }
  };
  //删除数据
  const deleteUser = async () => {
    if (JSON.stringify(rowId) === '{}') {
      message.warn('请选择需要删除的数据！');
      return;
    }
    const rep = await deleteUserApi(rowId);
    if (rep) {
      message.success('删除成功！');
      userData(1, 10);
    }
  };

  //修改相关
  const modifyUser = async (values: any, val: {}) => {
    setReviseList(val);
    setUpdateVisible(true);
    roleData();
    deptData();
    //对val里面角色和部门进行判断设置
    updateForm.setFieldsValue({ ...val });

    console.log('123', val);
  };
  //提交修改
  const searchValue = async (values: any) => {
    console.log(values);
    if (values.roleId) {
      values.roleId = values.roleId.toString();
    }
    const rep = await addUserApi(values);
    console.log(rep);
    if (rep) {
      message.success('修改成功！');
      setUpdateVisible(false);
      userData(1, 10);
    }
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
      width: '80px',
      sorter: true,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      key: 'ssex',
      align: 'center',
      width: '60px',
      render: (params) => {
        return params === '0'
          ? '男'
          : params === '1'
          ? '女'
          : params === '2'
          ? '保密'
          : '';
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      align: 'center',
      width: '100px ',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      key: 'deptName',
      align: 'center',
      width: '80px',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
      align: 'center',
      width: '80px',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: '60px',
      render: (params) => {
        return params == 1 ? (
          <Tag color="cyan">有效</Tag>
        ) : (
          <Tag color="volcano">锁定</Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: '100px',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
      width: '80px',
      fixed: 'right',
      render: (p1, p2) => {
        return (
          <>
            <span
              style={{ marginRight: '10PX' }}
              onClick={() => modifyUser(p1, p2)}
            >
              <SettingOutlined style={{ fontSize: '16px' }} />
            </span>
            <span>
              <EyeTwoTone style={{ fontSize: '16px', color: '#73d13d' }} />
            </span>
          </>
        );
      },
    },
  ];

  return (
    <div>
      <div>
        {/* 搜索 */}
        <SearchUse></SearchUse>
        <Button type="primary" onClick={showDrawer}>
          {' '}
          新增
        </Button>
        {/* 侧边栏 */}
        <Drawer
          title="新增用户"
          width={600}
          onClose={onClose}
          visible={visible}
          bodyStyle={{ paddingBottom: 80 }}
        >
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{ remember: true }}
            onFinish={addUser}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="password" label="密码">
              <Input />
            </Form.Item>
            <Form.Item name="email" label="邮箱">
              <Input />
            </Form.Item>
            <Form.Item name="mobile" label="手机号">
              <Input />
            </Form.Item>

            <Form.Item name="roleId" label="角色">
              <Select mode="multiple" allowClear style={{ width: '100%' }}>
                {roleList.map((item: any) => {
                  return (
                    <Option value={item.roleId} key={item.roleId}>
                      {item.roleName}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="deptId" label="部门ID">
              <Select>
                {deptList.map((item: any) => {
                  return (
                    <Option value={item.value} key={item.key}>
                      {item.title}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="status" label="状态" rules={[{ required: true }]}>
              <Radio.Group value={value}>
                <Radio value="0">锁定</Radio>
                <Radio value="1">有效</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item name="ssex" label="性别" rules={[{ required: true }]}>
              <Radio.Group value={value}>
                <Radio value="0">男</Radio>
                <Radio value="1">女</Radio>
                <Radio value="2">保密</Radio>
              </Radio.Group>
            </Form.Item>
            <Button>取消</Button>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              提交
            </Button>
          </Form>
        </Drawer>
        <Button onClick={deleteUser}>删除</Button>
      </div>
      <Table
        rowSelection={{
          type: 'checkbox',
          ...rowSelection,
        }}
        columns={columns}
        dataSource={data}
        scroll={{ x: 'calc(700px + 50%)', y: 480 }}
        pagination={{
          total: total,
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 30, 40, 50],
          onChange: userData,
        }}
      />
      {/* 修改相关 */}
      <Drawer
        title="修改用户"
        width={600}
        onClose={onClose}
        visible={updateVisible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Form
          form={updateForm}
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={searchValue}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true }]}
          >
            <Input type="text" />
          </Form.Item>

          <Form.Item name="email" label="邮箱">
            <Input value={reviseList.email} />
          </Form.Item>
          <Form.Item name="mobile" label="手机">
            <Input value={reviseList.mobile} />
          </Form.Item>

          <Form.Item name="roleId" label="角色">
            <Select mode="multiple" allowClear style={{ width: '100%' }}>
              {roleList.map((item: any) => {
                return (
                  <Option value={item.roleId} key={item.roleId}>
                    {item.roleName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item name="deptId" label="部门">
            <Select>
              {deptList.map((item: any) => {
                return (
                  <Option value={item.value} key={item.key}>
                    {item.title}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true }]}>
            <Radio.Group value={reviseList.status}>
              <Radio value="0">锁定</Radio>
              <Radio value="1">有效</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="ssex" label="性别" rules={[{ required: true }]}>
            <Radio.Group value={reviseList.ssex}>
              <Radio value="0">男</Radio>
              <Radio value="1">女</Radio>
              <Radio value="2">保密</Radio>
            </Radio.Group>
          </Form.Item>
          <Button>取消</Button>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
          >
            提交
          </Button>
        </Form>
      </Drawer>
    </div>
  );
}
